<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/26
 * Time: 18:02
 */
namespace App\Http\Controllers\web;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntMemberInfo;
use App\Module\EntMobileCode;
use App\Module\EntBookRenewLog;
use App\Module\EntMemberDRP;
use App\Module\EntPushMoneyLog;
use App\Module\EntOrderPrepaidLog;
use App\Module\EntReturnMsg;
use Session;
use Redirect, Validator, Cookie, Response, DB;

class LoginMaxController extends Controller
{
    protected $scaleOne = '0.3';
    protected $scaleTwo = '0.05';
    protected $scaleMoney = '2000';

    protected function checkMemberInfo($type, $name)
    {
        if ($type > 0) {
            switch ($type) {
                case 1:
                    $entMemberInfoOne = EntMemberInfo::select('MemNumber', 'UserName', 'States', 'MemEndTime')->where('DeleteMark', '1')->where('UserName', $name)->first();
                    return $entMemberInfoOne;
                    break;
                case 2:
                    $entMemberInfoTwo = EntMemberInfo::select('MemNumber', 'UserName', 'States', 'MemEndTime')->where('DeleteMark', '1')->where('WeiXID', $name)->first();
                    return $entMemberInfoTwo;
                    break;
            }
        } else {
            return '';
        }
    }


    public function pay()
    {
        $memNumber = $this->return_MemNumber();
        $str = $this->unifiedOrderXML();//返回统一下单所需的XML
        $mopenid = Session::get('OPENID');
        $prepay_id = $this->postUnifiedOrder($str);//返回prepay_id
        $payArray = $this->getPaySign($prepay_id);//支付所需参数
        $xmlOrder = simplexml_load_string($str);
        $out_trade_no = (string)$xmlOrder->out_trade_no;//订单
        $entOrderPrepaidLog = new EntOrderPrepaidLog();
        $entOrderPrepaidLog->WeiXID = $mopenid;
        $entOrderPrepaidLog->OrderNumber = $out_trade_no;
        $entOrderPrepaidLog->MemNumber = $memNumber;
        $entOrderPrepaidLog->AddDate = date('Y-m-d H:i:s', time());
        $entOrderPrepaidLog->save();
        return view('testpay.paymax', compact('payArray', 'out_trade_no', 'mopenid', 'memNumber'));
    }


    /**获取prepay_id
     * @param $para  统一下单XML
     * @return \SimpleXMLElement[]|string
     */
    protected function postUnifiedOrder($para)
    {
        $prepay_id = '';
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $responseText = $this->getHttpResponsePOST($url, $para);
        if ($responseText != '') {
            $xmlUnifiedOrder = simplexml_load_string($responseText);
            $prepay_id = (string)$xmlUnifiedOrder->prepay_id;
        }
        return $prepay_id;
    }

    /**生成统一下单参数
     * @return string 返回XML
     */
    protected function unifiedOrderXML()
    {
        $MOpenid = Session::get('OPENID');
        $appid = env('WEIXIN_APPID');//公众账号ID
        $mch_id = '1407661602';//商户号

        $device_info = 'WEB';//设备号--否
        $nonce_str = str_random(20);//随机字符串
        $sign = '';//签名
        $body = '老侯代读会费';//商品描述
        //$detail = '';//商品详情 --否

        $attach = '老侯代读会费';//附加数据 --否
        $out_trade_no = date('YmdH', time()) . str_random(6);//商户订单号
        $fee_type = 'CNY';//货币类型 --否
        $total_fee = '2000000';//总金额
        $spbill_create_ip = $this->get_real_ip();//终端IP
        $time_start = date('YmdHis', time());//交易起始时间 --否yyyyMMddHHmmss
        //$time_expire = '';//交易结束时间 --否yyyyMMddHHmmss

        //$goods_tag = '';//商品标记 --否
        $notify_url = 'http://wx.laohoulundao.com/pay/paysuccess.html';//通知地址
        $trade_type = 'JSAPI';//交易类型
        //$product_id = '';//商品ID --否
        //$limit_pay = '';//指定支付方式 --否
        $openid = $MOpenid;//用户标识 --否
        $orderXml = ['appid' => $appid, 'mch_id' => $mch_id, 'device_info' => $device_info, 'nonce_str' => $nonce_str, 'sign' => $sign, 'body' => $body, 'attach' => $attach, 'out_trade_no' => $out_trade_no, 'fee_type' => $fee_type, 'total_fee' => $total_fee, 'spbill_create_ip' => $spbill_create_ip, 'time_start' => $time_start, 'notify_url' => $notify_url, 'trade_type' => $trade_type, 'openid' => $openid];

        $orderXml['sign'] = $this->getSign($orderXml);
        return $this->foreachXML($orderXml);
    }

    /** 拼接XML
     * @param $array 统一下单参数
     * @return string
     */
    protected function foreachXML($array)
    {
        $xml = '<xml>';
        if (count($array) > 0) {
            foreach ($array as $key => $val) {
                if ($val != '') {
                    $xml .= '<' . $key . '>' . $val . '</' . $key . '>';
                }
            }
        }
        return $xml . '</xml>';
    }

    /**生成签名
     * @param $array 统一下单参数
     * @return string--获取 prepay_id 签名
     */
    protected function getSign($array)
    {
        /**
         * 生成sign签名
         * 注：签名不能包含sign以及空的值
         */
        $orderXmlSortStr = '';
        $orderXmlSort = array_sort_recursive($array);

        foreach ($orderXmlSort as $key => $val) {
            if ($val != '' && $key != 'sign') {
                $orderXmlSortStr .= $key . '=' . $val . '&';
            }
        }
        return strtoupper(md5($orderXmlSortStr . 'key=' . env('WEIXIN_PAYKEY')));
    }

    /**生成支付数组
     * @param $prepay_id
     * @return string  返回 paySign 签名
     */
    protected function getPaySign($prepay_id)
    {
        $str = '';
        $appId = env('WEIXIN_APPID');
        $timeStamp = $this->timeStamp();
        $nonceStr = str_random(20);
        $package = 'prepay_id=' . $prepay_id;
        $signType = 'MD5';
        $paySign = '';
        $payArray = ['appId' => $appId, 'timeStamp' => $timeStamp, 'nonceStr' => $nonceStr, 'package' => $package, 'signType' => $signType, 'sign' => $paySign];
        $payArray['sign'] = $this->getSign($payArray);
        return $payArray;
    }

    /**时间戳
     * @return bool|string
     */
    protected function timeStamp()
    {
        return strtotime('now');
    }

    /**获取客户端IP
     * @return bool
     */
    protected function get_real_ip()
    {
        static $realip;
        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")) {
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }

    /**
     * 远程获取数据，GET模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $cacert_url 指定当前工作目录绝对路径
     * return 远程输出的数据
     */
    protected function getHttpResponseGET($url)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        //curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);
        return $responseText;
    }

    /**
     * 远程获取数据，POST模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $cacert_url 指定当前工作目录绝对路径
     * @param $para 请求的数据
     * @param $input_charset 编码格式。默认值：空值
     * return 远程输出的数据
     */
    protected function getHttpResponsePOST($url, $para, $input_charset = '')
    {

        if (trim($input_charset) != '') {
            $url = $url . "_input_charset=" . $input_charset;
        }
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        //curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_POST, true); // post传输数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $para);// post传输数据
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);

        return $responseText;
    }



    //随机数字
    protected function RandStr($n)
    {
        $s = '';
        $str = "123456789"; // 输出字符集
        $len = strlen($str) - 1;
        for ($i = 0; $i < $n; $i++) {
            $s .= $str[rand(0, $len)];
        }
        return $s;
    }


    /** 添加支付记录
     * @param Request $request
     * @return string 3-失败 1-成功
     */
    public function payOrderStore(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $order = $request->json('order');
                $MOpenid = Session::get('OPENID');
                $memNumber = $this->return_MemNumber();
                if ($MOpenid != '' && $order != '' && $memNumber != '') {
                    $entBookRenewLog = new EntBookRenewLog();
                    $entBookRenewLog->MemNumber = $memNumber;
                    $entBookRenewLog->OrderNumber = $order;
                    $entBookRenewLog->RenewDesc = '会员缴费';
                    $entBookRenewLog->WeiXID = $MOpenid;
                    $entBookRenewLog->AddDate = date('Y-m-d H:i:s', time());
                    $entBookRenewLog->save();
                    if ($entBookRenewLog) {
                        $upEntMemberInfo = EntMemberInfo::where('WeiXID', $MOpenid)->update(['States' => 1, 'RegisterType' => 2, 'MemEndTime' => date('Y-m-d H:i:s', strtotime("+1 year"))]);
                        EntOrderPrepaidLog::where('WeiXID', $MOpenid)->where('OrderNumber',$order)->delete();
                        $result = '1';
                    }
                } else {
                    if ($MOpenid != '') {
                        $upEntMemberInfo = EntMemberInfo::where('WeiXID', $MOpenid)->update(['States' => 1, 'RegisterType' => 2, 'MemEndTime' => date('Y-m-d H:i:s', strtotime("+1 year"))]);
                        $result = '1';
                    } else {
                        $result = '3';
                    }


                }
            }
        } catch (Exception $e) {
            $result = '3';
        }
        return $result;
    }
    public function paysuccess(Request $request)
    {
        $msg = array();
        $postStr = file_get_contents('php://input');
        $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $entReturnMsg=new EntReturnMsg();
        $entReturnMsg->Msg= json_encode($msg);
        $entReturnMsg->TypeName='支付描述';
        $entReturnMsg->AddDate=date('Y-m-d H:i:s', time());
        $entReturnMsg->save();
        return view('pay.paysuccess');
    }
    protected function return_MemNumber()
    {
        $i = 0;
        try {
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            if ($MName != '' && $MKey != '') {
                $entMemberInfo = EntMemberInfo::select('MemNumber')->where('UserName', $MName)->where('LoginKey', $MKey)
                    ->where('DeleteMark', '1')
                    ->first();
                if (count($entMemberInfo) > 0) {
                    $i = $entMemberInfo->MemNumber;
                }
            }
        } catch (ModelNotFoundException $e) {
            $i = 0;
        }
        return $i;
    }
}